//
//  UIColor+helper.m
//  Kline
//
//  Created by zhaomingxi on 14-2-9.
//  Copyright (c) 2014年 zhaomingxi. All rights reserved.
//

#import "UIColor+helper.h"

@implementation UIColor (helper)

#pragma mark 16进制颜色转换
+ (UIColor *) colorWithHexString: (NSString *)color {
    return [self colorWithHexString:color withAlpha:1.0];
}

// color = #FFFFFF 或者 0xFFFFFF
+ (UIColor *) colorWithHexString: (NSString *)color withAlpha:(CGFloat)alpha
{
    unsigned int r, g, b;
    colorModel *rgb = [self RGBWithHexString:color withAlpha:alpha];
    r = rgb.R;
    g = rgb.G;
    b = rgb.B;
    alpha = rgb.alpha;
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:alpha];
}

#pragma mark 16进制转换为RGB模式
+ (colorModel *) RGBWithHexString: (NSString *)color withAlpha:(CGFloat)alpha{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return nil;
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    
    //为6时，格式为RGB；为8时，格式为ARGB
    if ([cString length] != 6 && [cString length] != 8){
        return nil;
    }
    
    NSString *regex = @"^[A-Fa-f0-9]+$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    if (![pred evaluateWithObject:cString]) {
        return nil;
    }

    
    // Separate into r, g, b substrings
    NSUInteger start = 0;
    if ([cString length] == 8) {
        start = 2;
    }
    
    NSRange range;
    range.location = start;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location += 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location += 2;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    colorModel *rgb = [[colorModel alloc] init];
    rgb.R = r;
    rgb.B = b;
    rgb.G = g;
    if ([cString length] == 8) {
        unsigned int a = 0;
        NSString *aString = [cString substringToIndex: 2];
        [[NSScanner scannerWithString: aString] scanHexInt: &a];
        rgb.alpha = 1.0 * a / 255;
    }
    else {
        rgb.alpha = alpha;
    }
    
    return  rgb;
}

@end
